// Package promise my dream
package promise

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	"strconv"
	"strings"

	"golang.org/x/text/encoding/simplifiedchinese"
	"golang.org/x/text/transform"
)

//DecodeGBK is DecodeGBK
func DecodeGBK(s []byte) ([]byte, error) {
	I := bytes.NewReader(s)
	O := transform.NewReader(I, simplifiedchinese.GBK.NewDecoder())
	d, e := ioutil.ReadAll(O)
	if e != nil {
		return nil, e
	}
	return d, nil
}

//EncodeGBK convert UTF-8 to GBK
func EncodeGBK(s []byte) ([]byte, error) {
	I := bytes.NewReader(s)
	O := transform.NewReader(I, simplifiedchinese.GBK.NewEncoder())
	d, e := ioutil.ReadAll(O)
	if e != nil {
		return nil, e
	}
	return d, nil
}

//Process deal Process
type Process struct {
}

//IsWindowProcessAliveByName test
func (ps *Process) IsWindowProcessAliveByName(strName string) bool {

	strName += ".exe"

	//out, err := exec.Command("bash", "-c", "ps cax | grep myapp").Output()
	//tasklist /fi "imagename eq chrome.exe"
	//https://www.windows-commandline.com/tasklist-command/
	//https://superuser.com/questions/669964/batch-if-exe-is-not-running
	param := "tasklist /fi " + "IMAGENAME  eq chrome.exe"
	//https://www.cnblogs.com/saryli/p/11652294.html
	//https://mlog.club/article/1178469
	//param := "tasklist"
	fmt.Println(param)

	arg := []string{"/FI", "imagename eq chrome.exe"}
	cmd := exec.Command("tasklist", arg...)

	//cmd := exec.Command("tasklist", "/fi", "chrome.exe")
	data, err := cmd.CombinedOutput()
	fmt.Println(string(data))
	//CombinedOutput runs the command and returns its combined standard output and standard error
	//https://www.jianshu.com/p/2237f423afcf
	if err != nil && err.Error() != "exit status 1" {
		fmt.Println("ServerMonitor", err)
		return false
	}
	//输出乱码https://kyakya.icu/golang-exec%E6%8E%A7%E5%88%B6%E5%8F%B0%E4%B9%B1%E7%A0%81
	//Golang 中的 UTF-8 与 GBK 编码转换

	s, _ := EncodeGBK(data)
	strData := string(s)
	fmt.Println(string(strData))
	if strings.Contains(strData, strName) {
		return true
	}
	return true
}

//IsProcessExist IsProcessExist
func IsProcessExist(appName string) (bool, string, int) {
	appary := make(map[string]int)
	cmd := exec.Command("cmd", "/C", "tasklist")
	output, _ := cmd.Output()
	//fmt.Printf("fields: %v\n", output)
	n := strings.Index(string(output), "System")
	if n == -1 {
		fmt.Println("no find")
		os.Exit(1)
	}
	data := string(output)[n:]
	fields := strings.Fields(data)
	for k, v := range fields {
		if v == appName {
			appary[appName], _ = strconv.Atoi(fields[k+1])

			return true, appName, appary[appName]
		}
	}

	return false, appName, -1
}
